package com.qf.smsplatform.interceptor;
/*2021/11/2*/

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.smsplatform.cache.TMenuCache;
import com.qf.smsplatform.constans.ResultCode;
import com.qf.smsplatform.dto.R;
import com.qf.smsplatform.pojo.TMenu;
import org.omg.PortableInterceptor.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @YuTao
 */
@Component
public class UrlInterceptor implements HandlerInterceptor {

    private TMenuCache tMenuCache;
    @Autowired
    public void settMenuCache(TMenuCache tMenuCache) {
        this.tMenuCache = tMenuCache;
    }

    private ObjectMapper objectMapper;
    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


//        我是拦截到的访问地址样式：/smsplatform/black/selectBA

        //获取用户访问的地址
        String requestURI = request.getRequestURI();
//        System.out.println("我是当前访问的地址"+requestURI);
        //对当前路径进行截取，符合数据库中的存储规则，进行对比
        int i = requestURI.substring(1).indexOf("/");//获取第二个/的下标
        String url = requestURI.substring(i+1);//进行第二个/后地址的截取
        //从缓存中获取登录地址的状态，判断是否有权限进行访问
        TMenu menu = tMenuCache.getByKey(url);
        //对数据库中没有的地址和没有访问权限的地址进行拦截
        if (menu==null ||menu.getState()==0){
            R r = R.setError(ResultCode.NOT_ALLOWED, "用户没有权限访问该地址", null);
            response.setContentType("application/jackson;charset=utf-8");
            response.getWriter().write(objectMapper.writeValueAsString(r));
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
